<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class erpAction extends BackAction{
    
    function _getKey(){
        include_once( ROOT . '/bin/config.php' );
        include_once( ROOT . '/bin/weibooauth.php' );
        return new WeiboClient( '4171612386' , '5d494442822b86c6792acb1d2791bc31' , 'db25cf6a50558c502ea1bfe7a8fd1552' , 'bb45cb2ee71f5ad6b98d0676dc24989a');
    }
    
    function actionIndex(){
        $this->setPageTitle('微博活动监测');
        $this->render('new');
    }
    
    function actionNew(){
        $this->setPageTitle('微博活动监测');
        $this->render();
    }
    
    function actionResult(){
        header('Content-Type:text/html;charset:utf-8');
        $this->setPageTitle('转发评论');
        $blog_id    = $this->params['blog_id'];
        $page       = $this->params['page'];
        if(!$blog_id){
            echo '未监测此微博活动';
            exit;
        }
        
        $page   = intval($page);
        
        if($page<=1){
            $offset = 0;
        }else{
            $offset = ($page-1) * 30;
        }
        //微博活动信息
        $blog    = ORM_Finder::findOne(DB_ERP_BLOG, array('blog_id'=>$blog_id));
        
        $rs     = ORM_Finder::find('DB_ERP_RESULT', array('blog_id'=>$blog_id));
        $total = ORM_Finder::findCount('DB_ERP_RESULT', array('blog_id'=>$blog_id));
        
        $pager  = new Pager(url_for('erp/result?blog_id='.$blog_id.'&page='), $total, 30);
        $pager->SetCurPage($page);
        $pager  = $pager->GetNavigation();
        
        $this->set('rs', $rs);
        $this->set('blog', $blog);
        $this->set('pager', $pager);
        $this->render();        
        
    }
    
    function actionList(){
        header('Content-Type:text/html;charset:utf-8');
        $this->setPageTitle('转发评论');
        $blog_id    = $this->params['blog_id'];
        $page       = $this->params['page'];
        if(!$blog_id){
            echo '未监测此微博活动';
            exit;
        }
        $page   = intval($page);
        if($page<=1){
            $offset = 0;
        }else{
            $offset = ($page-1) * 30;
        }
        
        $sql     = " from {#prefix#}".DB_ERP_PING::getTableName().' as a left join {#prefix#}'.DB_ERP_ZHUANFA::getTableName();
        $sql     = $sql .' as b on a.user_id=b.user_id where a.blog_id ="'.$blog_id.'" and b.blog_id ="'.$blog_id.'" order by a.created_at desc ';
        
        $rs      = ORM_Finder::findBySql('DB_ERP_BLOG', "select distinct a.user_id,a.user ".$sql.' limit '.$offset.',30');
        if(!$rs){
            echo '没有转发+评论的微博主。';
            exit;
        }
        //微博活动信息
        $blog    = ORM_Finder::findOne(DB_ERP_BLOG, array('blog_id'=>$blog_id));
        
        $total   = ORM_Finder::execSql("select count(distinct a.user_id) ".$sql, array(), DB_ERP_BLOG);
        $pager  = new Pager(url_for('erp/list?blog_id='.$blog_id.'&page='), $total, 30);
        $pager->SetCurPage($page);
        $pager  = $pager->GetNavigation();
        
        $this->set('rs', $rs);
        $this->set('blog', $blog);
        $this->set('pager', $pager);
        $this->render();
    }
    
    /**
     * 创建活动监测
     */
    function actionCreate(){
        $url        = trim($this->postVar('url'));
        $url        = explode('/', $url);
        $len        = count($url);
        $inx        = $len -2;
        $weibo_id   = $url[$inx];
        $url        = $url[$len-1];
        
        $rs = ORM_Finder::findOne('DB_ERP_BLOG', array('mid'=>$url));
        if($rs){
            $this->redirect('erp/result?blog_id='.$rs->getBlogId());
            exit;
        }
        $c  = $this->_getKey();
        $id = $c->query_id($url);
        if(!isset ($id['id'])){
            echo $id['error'];
            exit;
        }
        $id = $id['id'];
        $rs = new DB_ERP_BLOG();
        $rs->setBlogId($id);
        $rs->setMid($url);
        $rs->setIsActive(1);
        $rs->setWeiboId($weibo_id);
        $rs->save();
        $this->redirect('erp/spider_zhuanfa?blog_id='.$id);
    }
    
    /**
     * 抓取转发
     */
    function actionSpiderZhuanfa(){
        
        $c          = $this->_getKey();
        $limit      = empty($this->params['limit'])?0:$this->params['limit'];
        $blog_id    = $this->params['blog_id'];
        
        if(!$blog_id){
            $task       = ORM_Finder::findOne('DB_ERP_BLOG', array('is_active'=>1), '*', 'id asc',"$limit ,1");
        }else{
            $task       = ORM_Finder::findOne('DB_ERP_BLOG', array('blog_id'=>$blog_id));
        }
        
        if(!$task){
            echo 'no task';
            exit;
        }
        $blog_id     = $task->getBlogId();
        $msg         = $c->repost_timeline($blog_id, 1, 200);
        
        if ($msg === false || $msg === null){
                echo "Error occured";
                exit;
        }
        if (isset($msg['error_code']) && isset($msg['error'])){
                echo ('Error_code: '.$msg['error_code'].';  Error: '.$msg['error'] );
                Common::mailto('erp.591zan.com转发抓取失败', $msg['error']);
                exit;
        }
        $re = array();
        foreach ($msg as $k => $v) {
            $re[]   = DB_ERP_ZHUANFA::store_zhuanfa($v);
        }
        
        if($this->params['blog_id']){
            $this->redirect('erp/spider_ping?blog_id='.$blog_id);
        }
        echo 'ok';
    }
    
    function actionSpiderPing(){
        
        $c          = $this->_getKey();
        $limit      = empty($this->params['limit'])?0:$this->params['limit'];
        $blog_id    = $this->params['blog_id'];
        if(!$blog_id){
            $task       = ORM_Finder::findOne('DB_ERP_BLOG', array('is_active'=>1), '*', 'id asc',"$limit ,1");
        }else{
            $task       = ORM_Finder::findOne('DB_ERP_BLOG', array('blog_id'=>$blog_id));
        }
        
        if(!$task){
            echo 'no task';
            exit;
        }
        $blog_id     = $task->getBlogId();
        $msg         = $c->get_comments_by_sid($blog_id, 1, 200);
        if ($msg === false || $msg === null){
                echo "Error occured";
                exit;
        }
        if (isset($msg['error_code']) && isset($msg['error'])){
                echo ('Error_code: '.$msg['error_code'].';  Error: '.$msg['error'] );
                Common::mailto('erp.591zan.com评论抓取失败', $msg['error']);
                exit;
        }
        $re = array();
        foreach ($msg as $k => $v) {
            $re[]   = DB_ERP_PING::store_ping($v);
        }
        if($this->params['blog_id']){
            $this->redirect('erp/result?blog_id='.$blog_id);
        }
        echo 'ok';
    }
    
    function actionFilter(){
        $action     = $this->params['act'];
        $blog_id    = $this->params['blog_id'];
        
        if(!$blog_id){
            $this->redirect($_SERVER['HTTP_REFERER']);
        }
        
        $blog    = ORM_Finder::findOne(DB_ERP_BLOG, array('blog_id'=>$blog_id));
        
        if(!$blog){
            $this->redirect($_SERVER['HTTP_REFERER']);
        }
        
        if($action=='open'){
            $blog->setIsActive(1);
        }else{
            $blog->setIsActive(0);
        }

        $blog->save();
        $this->redirect('list?blog_id='.$blog_id);
    }
    
    /**
     * 检测同时转发和评论的人
     */
    function actionSpiderResult(){
        $sql     = "select b.blog_id,z.user_id,z.user,z.text from {#prefix#}".  DB_ERP_BLOG::getTableName().' as b left join {#prefix#}'.DB_ERP_PING::getTableName();
        $sql     = $sql . " as z on b.blog_id=z.blog_id";
        $rs      = ORM_Finder::findBySql('DB_ERP_BLOG',$sql);
        $re      = array();
        
        foreach ($rs as $k => $v) {
            $has    = ORM_Finder::findOne('DB_ERP_PING', array('user_id'=>$v['user_id'],'blog_id'=>$v['blog_id']));
            $num    = substr_count($has->getText(), '@');
            $has->setPingAt($num);
            $has->save();
            if(!$has){
                continue ;
            }
            $user   = unserialize($v['user']);
            $re[]   = DB_ERP_RESULT::store($v['user_id'], $v['blog_id'], $user['screen_name'],$num);
        }
        echo "ok";
    }
    
    /**
     * 关注检测
     */
    function actionSpiderFollow(){
        $rs = ORM_Finder::find(DB_ERP_BLOG, array('is_active'=>1, 'is_follow'=>1));
        if(!$rs){
            echo 'no data';
            exit;
        }
        
        foreach ($rs as $k => $v) {
            
            $has    = ORM_Finder::find('DB_ERP_RESULT', array('follow_me'=>'未知','blog_id'=>$v->getBlogId()));
            if(!$has){
                continue;
            }
            
            
            foreach ($has as $k1 => $v1){
                
                $c          = $this->_getKey();
                $target = $v1->getUserId();
                $source = $v->getWeiboId();
                $msg = $c->friendships_exists($target, $source);

                if ($msg === false || $msg === null){
                        echo "Error occured";
                        continue;
                }
                if (isset($msg['error_code']) && isset($msg['error'])){
                        echo ('Error_code: '.$msg['error_code'].';  Error: '.$msg['error'] );
                        Common::mailto('获取关系错误', $msg['error']);
                        continue ;
                }
                
                $follow     = array('0' =>"未关注",'已关注');
                $friends    = (int)$msg['friends'];
                $v1->setFollowMe($follow[$friends]);
                $v1->save();
            }
        }
        echo 'ok';
    }
}
?>
